<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/11
 * Time: 19:59
 */

namespace app\base\library;


use app\base\model\Menu;
use app\base\model\Role;
use think\Session;
use \think\facade\Request;

class Auth
{
    protected $role;
    protected $role_id;
    protected $error;
    protected $auth_rule;
    protected $uncheck_rule = [
        'base/index/index',
        'base/index/main',
        'base/manager/changepwd',

    ];

    /**
     * Auth constructor.
     * @param $role_id 角色id
     */
    public function __construct()
    {
        $this->role = new Role();
        $this->auth_model = new Menu();

    }

    /**
     * 获取角色 授权的 ids
     */
    public function get_role_auth($role_id){
        $this->role_id = explode(',',$role_id);
        $roleModel = $this->role;
        $role = $roleModel->field('id,role_name,auth_ids')->where('id' ,'in',$this->role_id)->select()->toArray();

        if(!$role) {
            $this->error = '该用户没有归属的角色';
            return false;
        }
        $role_arr = [
            'id' => '',
            'role_name' => '',
            'auth_ids' => '',
        ];
        foreach($role as $k => $v){
            $role_arr['id'] .= $v['id'].',';
            $role_arr['role_name'] .= $v['role_name'].',';
            $role_arr['auth_ids'] .= $v['auth_ids'].',';
        }

        $role_arr['id'] = rtrim($role_arr['id'] ,',');
        $role_arr['role_name'] = rtrim($role_arr['role_name'] ,',');
        $role_arr['auth_ids'] = rtrim($role_arr['auth_ids'] ,',');

        return $role_arr;
    }

    /**
     * 检查角色权限
     * @param $role_info array 角色信息，授权的ids 角色的id
     */
    public function check_auth($role_info){

        //超级管理员 不验证
        if(in_array(1 ,explode(',',$role_info['id']))) return true;

        $auth = $this->auth_model
                    ->field('module,controller,action')
                    ->where('id','in',$role_info['auth_ids'])
                    ->select()->toArray();

        if(!$auth){
            $this->error = '获取权限失败';
            return false;
        }

        //下划线替换成空
        foreach($auth as $k => $v){
            $auth[$k]['controller'] = strtolower(str_replace('_','',$v['controller']));
        }



        $request_url = strtolower(Request::module().'/'.Request::controller().'/'.Request::action());

        //检查请求的地址是否是免check的节点
        if(in_array($request_url,$this->uncheck_rule))  return true;

        $request_arr = [
            'module' => strtolower(Request::module()),
            'controller' => strtolower(Request::controller()),
            'action' => strtolower(Request::action()),
        ];

        if(!in_array($request_arr,$auth)){
            $this->error = '您没有权限';
            return false;
        }


        return true;

    }


    /**
     * 获取错误
     */
    public function getError(){
        return $this->error;
    }
}